<?php


namespace Soen\Container;


use Psr\Container\ContainerInterface;

class Container implements ContainerInterface
{
    public $services = [];
    public $components = [];
    public $servicesPath = '';

    function __construct($path)
    {
        $server = new Server($path);
        $this->components = $server->load();
    }

    function get($id){
        return $this->components[$id];
    }

    public function set($id, $config){
		$this->components[$id] = $config + $this->components[$id];
    }


	/**
	 * @param $id
	 * @param $componentObject
	 */
	public function setServer($id, $componentObject){
		$this->services[$id] = $componentObject;
	}

    /**
     * @param string $id
     * @return mixed
     */
    function getServer(string $id){
        $service = isset($this->services[$id]) ? $this->services[$id] : null;
        if($service){
	        $initMethod = (isset($this->components[$id]['init']) && (string)$this->components[$id]['init']) ? $this->components[$id]['init'] : '';
	        if($initMethod){
		        return $service->$initMethod();
	        }
        }
	    return $service;
    }

    public function has($id)
    {
        return isset($this->components[$id]);
    }

    public function hasServer($id)
    {
        return isset($this->services[$id]);
    }
    
    public function add($id, $component){
        $this->components[$id] = $component;
    }
}